<template>
  <div class="data_source_container">
    <!--    <input @change="testAdmin2" type="file">-->
<!--    <BatchRecharge :currency="['CNY','USD']" url="https://gd123.vip/stockadmin/member/batch/recharge" jy-password="123" token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJhZG1pbiIsImxvZ2luSWQiOjEsInJuU3RyIjoiVXlFTnMydDN5Z1l2TXplcnU5ZXlpcWZkQ1k3YkdVRVUifQ.BfIvkeRhce7SzZMwmKWEF0-k3Vem3l4Hga134dE_fDs" >批量充值</BatchRecharge>-->
    <div class="main_box">
      <ul class="server_list">
        <li v-for="(server,$index) in pageData.serverList" v-if="pageData.serverList" :key="$index" class="server"
            @click="selectServer(server)">
          <div class="server_info">
            <div class="server_name">
              <h3>{{ server.serverName }}</h3>
              <p :class="['status',matchStateClass(server.serverStatus)]">
                {{ matchStateText(server.serverStatus) }}
              </p>
            </div>
            <p class="porto">{{ `协议: ${server.serverProto}` }}</p>
            <div class="server_url">
              <p>{{ `数据源地址: ${server.serverUrl}` }}</p>
              <button class="copy">复制</button>
            </div>
          </div>
          <div class="control_btn">
            <button @click.stop="runServer(server.serverCode,$index)" style="color: #02c73f">启动</button>
            <button @click.stop="stopServer(server.serverCode,$index)" style="color: #666666">停止</button>
            <button style="color: #168dff">测试</button>
          </div>
        </li>
      </ul>
      <div class="stock_data">
        <ul class="stock_list child_box">
          <li v-for="(stock,$index) in currentStockList" v-if="currentStockList" :key="$index" class="stock">
            <p>{{ stock }}</p>
          </li>
        </ul>
        <div class="push_text child_box">
          <div class="title">
            <p>当前推送内容</p>
          </div>
          <div class="text">
            <json-viewer
                :expand-depth="2"
                :value="currentStockPushText"
                class="w-100% json-v"
                copyable
            ></json-viewer>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, reactive} from "vue";
import {changeDataSource, getServerListApi, runServerApi, stopServerApi} from "@/api/server-control-api/server-control-api";
import axios from "axios";
import EncryptText from "@/components/common/text/EncryptText";

onMounted(() => {
  changeDataSource({dataSourceName: "AllTick"}).then(res => {
    console.log(res)
  })
  //initData()
})
const initData = () => {
  pageData.serverList = []
  loadServerList({
    dataSourceName: "YuFeng"
  })
}

const currentStockList = computed(() => {
  if (pageData?.serverList?.length > 0) {
    const foundServer = pageData.serverList.find(server => {
      return server.serverCode === pageData.currentStock
    })
    if (foundServer) {
      return foundServer.pushList
    }
  }
  return []
})

const currentStockPushText = computed(() => {
  if (pageData?.serverList?.length > 0) {
    const foundServer = pageData.serverList.find(server => {
      return server.serverCode === pageData.currentStock
    })
    console.log(foundServer)
    if (foundServer?.pushContent) {
      return JSON.parse(foundServer.pushContent)
    }
  }
  return "没有推送"
})

const pageData = reactive({
  currentStock: "YuFeng",
  serverList: [
    {
      serverName: "誉峰",
      serverCode: "YuFeng",
      serverUrl: "127.0.0.1:9000/mock",
      serverProto: "websocket",
      serverStatus: "1",
      pushContent: "",
      pushList: [
        "SZ123152", "SH151235", "SZ123152", "SZ123152", "SH151235", "SZ123152", "SH151235", "SZ123152", "SH151235",
      ]
    },
    {
      serverName: "誉峰指数",
      serverCode: "YuFengIndex",
      serverUrl: "127.0.0.1:9001/mock",
      serverProto: "websocket",
      serverStatus: "2",
      pushList: [
        "SZ123152", "SH151235", "SZ123152", "SH151235", "SZ123152", "SH151235",
      ]
    },
    {
      serverName: "Polygon",
      serverCode: "Polygon",
      serverUrl: "127.0.0.1:9002/mock",
      serverProto: "websocket",
      serverStatus: "1",
      pushList: [
        "SZ123152", "SH151235", "SZ123152", "SH151235", "SZ123152", "SH151235",
      ]
    },
    {
      serverName: "AllTick",
      serverCode: "AllTick",
      serverUrl: "127.0.0.1:9003/mock",
      serverProto: "websocket",
      serverStatus: "3",
      pushList: [
        "SZ123152", "SH151235", "SZ123152", "SH151235", "SZ123152", "SH151235",
      ]
    },
  ],
});

const matchStateClass = (status) => {
  const statusMap = {
    "1": "run",
    "2": "stop",
    "3": "err",
  }
  return statusMap[status]
}
const matchStateText = (status) => {
  const statusMap = {
    "1": "运行",
    "2": "停止",
    "3": "异常",
  }
  return statusMap[status]
}

const selectServer = (server) => {
  pageData.currentStock = server.serverCode
}
const loadServerList = async () => {
  const res = await getServerListApi()
  console.log(res)
  if (res.suc) {
    pageData.serverList = res.data
  }
}
const testAdmin = (event) => {
  var file = event.target.files[0];
  console.log(file)
  const formData = new FormData();
  formData.append('file', file); // 替换为实际文件对象
  console.log("111")
  console.log(formData.get("file"))
}
const testAdmin2 = (event) => {
  var file = event.target.files[0];
  console.log(file)
  // 构造 FormData 对象
  const formData = new FormData();
  formData.append('file', file); // 替换为实际文件对象
  formData.append('currency', 'CNY');
  formData.append('jyPassword', '123');
  try {
    console.log(formData.get("file"))
    // 发送请求
    const response = axios({
      method: 'post',
      url: 'https://gd123.vip/stockadmin/member/batch/recharge',
      headers: {
        'admin-auth-token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJhZG1pbiIsImxvZ2luSWQiOjEsInJuU3RyIjoiRHBMN3hFemgydlFTVElrQWJSZ2pRSTg5VXI1czR5OU8ifQ.HoSIDIv46gjwmDIl1l-8o3Fvf0-yis4-PND_2kpRV1w',
      },
      data: formData,
      responseType: 'blob',
    });
    // 获取文件名（从响应头或默认值）
    // const contentDisposition = response.headers['content-disposition'];
    // const filename = contentDisposition
    //     ? decodeURIComponent(contentDisposition.split('filename=')[1].replace(/"/g, ''))
    //     : 'downloaded_file';
    // console.log("4")
    // 创建 Blob 对象并触发下载
    //const blob = new Blob([response.data], {type: response.headers['content-type']});
    response.then(res=>{
      console.log(res)
      const blob = new Blob([res.data], {type: 'content-disposition'});
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = "output.xlsx";
      link.click();
      // 释放 URL 对象
      URL.revokeObjectURL(link.href);
    })

  } catch (error) {
    console.error('请求失败:', error.response ? error.response.data : error.message);
  }
}

const stopServer = async (serverCode, index) => {
  const res = await stopServerApi(serverCode)
  if (res.suc) {
    console.log("关闭成功",pageData.serverList[index])
    pageData.serverList[index].serverStatus = res.data.serverStatus
  }
}

const runServer = async (serverCode, index) => {
  const res = await runServerApi(serverCode)
  if (res.suc) {
    pageData.serverList[index].serverStatus = res.data.serverStatus
  }
}
</script>
<style lang="scss">
.data_source_container {
  height: 100vh;
  width: 100vw;
  background-color: #d2d2d2;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;

  ::-webkit-scrollbar {
    display: none;
  }

  .main_box {
    max-width: 1000px;
    max-height: 600px;
    width: 80vw;
    height: 80vh;
    background-color: #ffffff;
    border-radius: 5px;
    box-shadow: rgba(0, 0, 0, .1) 0 0 15px 5px;
    display: flex;
    padding: 10px 0;
    box-sizing: border-box;

    .server_list {
      height: 100%;
      border-right: 1px solid #e0e0e0;
      padding: 0 10px;
      flex: 0.8;
      flex-direction: column;
      overflow: auto;

      ::-webkit-scrollbar {
        display: none;
      }

      .server {
        margin: 10px 0;
        display: flex;
        height: 120px;
        background-color: #f8f8f8;
        border-radius: 5px;
        align-items: center;
        padding: 10px;
        box-sizing: border-box;
        justify-content: space-between;
        box-shadow: 2px 2px 5px rgba(0, 0, 0, .1);

        &:first-child {
          margin: 0;
        }

        .server_info {
          width: 80%;
          height: 100%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          gap: 5px;

          .server_name {
            display: flex;

            h3 {
              font-size: 16px;
              font-weight: 500;
              color: #2171b6;
              padding: 0;
              margin: 0;
            }

            .status {
              margin-left: 5px;
              font-size: 10px;
              line-height: 15px;

              &.run {
                color: #02c73f;
              }

              &.stop {
                color: #6a6a6a;
              }

              &.err {
                color: #cb5959;
              }
            }
          }

          .porto {
            font-size: 10px;
            color: #9c9c9c;
          }

          .server_url {
            display: flex;
            align-items: center;
            gap: 5px;

            p {
              font-size: 12px;
              color: #999999;
            }

            > button {
              border: none;
              font-size: 12px;

              background-color: transparent;
              color: #168dff;
              border-radius: 3px;
            }
          }
        }

        .control_btn {
          display: flex;
          flex-direction: column;
          height: 100%;
          justify-content: space-between;

          button {
            border: none;
            background-color: white;
            padding: 5px 10px;
            font-size: 12px;
            border-radius: 5px;
          }
        }
      }
    }

    > .stock_data {
      flex: 1.5;
      height: 100%;
      padding: 0 10px;
      box-sizing: border-box;
      display: flex;
      gap: 10px;

      > .child_box {
        border-radius: 10px;
        box-shadow: 3px 3px 5px rgba(0, 0, 0, .1);
      }

      .stock_list {
        width: 40%;
        background-color: #f8f8f8;
        gap: 0.5vw;
        padding: 5px;
        box-sizing: border-box;
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        align-content: flex-start;

        > .stock {
          flex-shrink: 0;

          p {
            border: 1px solid #2171b6;
            color: #2171b6;
            padding: 0 3px;
            font-size: 10px;
            border-radius: 4px;
          }
        }
      }

      .push_text {
        flex: 1;
        background-color: #f8f8f8;
        display: flex;
        flex-direction: column;
        padding-bottom: 10px;

        .title > p {
          padding-top: 10px;
          padding-left: 10px;
          font-size: 14px;
          color: #03b4d2;
          background-color: white;
          border-radius: 10px 10px 0 0;
          background-color: #f8f8f8;
        }

        .text {
          overflow: auto;
          border-radius: 0 0 10px 10px;

          ::-webkit-scrollbar {
            display: none;
          }
        }

        .json-v {
          font-size: 12px;
          background-color: #f8f8f8;
        }
      }
    }
  }
}

</style>
